package cn.dakaqi.open.api.v1;

import cn.dakaqi.entities.*;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.*;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.vo.response.ActivityApplyVO;
import cn.dakaqi.vo.response.ActivityVO;
import cn.dakaqi.vo.response.DKQPage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wordnik.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.MediaTypes;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/7.
 * 活动
 */
@RestController
@RequestMapping(value = "/api/v1/activity")
@Api(value = "活动API")
public class ActivityRestController
{
    private static Logger logger = LoggerFactory.getLogger(ActivityRestController.class);

    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    ActivityService activityService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    ActivityApplyService activityApplyService;
    @Autowired
    ActivityRecruitService activityRecruitService;
    @Autowired
    ConfigUtil configUtil;


//    志愿者一号通：所在团体的省编号（2位）+所在省人数排序编号（8位，剩下的补0）+随机数（1位）
//
//    志愿团体一号通：所在团组织机构代码（后9位）+排序号（3位）
//
//    活动一号通： 1.体制内团体的活动—发布活动的团体所在团组织的省份（2位）+创建时间年份（4位）+排序号（7位）
//                2.社会团体—发布活动的团体所在的省份（2位）+创建时间年份（4位）+排序号（7位）

    /**
     * 发布新活动
     * @param param
     * @return
     */
    @RequestMapping(value = "/create",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> create(@RequestBody String param)
    {
        JsonResult result = new JsonResult();
        try
        {
            //检查非空
            if(StringUtils.isBlank(param))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            List<Activity> activityList = this.activityService.save(param, ConfigUtil.getClientId());
            if(null != activityList && activityList.size()>=1)
            {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("groupCode", activityList.get(0).getGroup().getGroupCode());
                resultMap.put("list", activityList);
                result.setData(resultMap);
            }
            result.setMessage("活动发布成功");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    /**
     * 修改活动
     * @param param
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> update(@RequestBody String param)
    {
        JsonResult result = new JsonResult();
        try
        {
            //检查非空
            if(StringUtils.isBlank(param))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            this.activityService.update(param);
            result.setMessage("活动发布成功");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    /**
     * 查询指定社团的所有活动（当前用户在本次活动的身份）
     * @param groupCode
     * @param memberCode
     * @param pageNumber
     * @return
     */
    @RequestMapping(value = "/group/{groupCode}/{memberCode}/{pageNumber}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> findByGroupAndMemberCode(@PathVariable("groupCode") String groupCode,@PathVariable("memberCode") String memberCode,@PathVariable("pageNumber") int pageNumber)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            Page<Activity>  data = this.activityService.findByGroupCode(groupCode, pageNumber);
            if (data == null || data.getContent() == null || data.getContent().size() ==0)
            {
                String message = "暂无活动数据";
                logger.warn(message);
                jsonResult.setMessage(message);
                jsonResult.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(jsonResult,HttpStatus.OK);
            }
            Map<String,Object> resultMap = new HashMap<String,Object>();

            List<Activity> list = data.getContent();
            List<ActivityVO> vos = new ArrayList<ActivityVO>();
            for(Activity activity:list)
            {
                ActivityRecruit activityRecruit = this.activityRecruitService.findByActivity(activity.getId());
                ActivityVO vo = ActivityVO.buildVO(activity,activityRecruit,ConfigUtil.getClientId());
                if(null != memberCode && !"null".equals(memberCode) && StringUtils.isNotBlank(memberCode))
                {
                    ActivityApply apply = activityApplyService.findByVolunteerAndActivity(memberCode, activity.getActivityCode());
                    if(null != apply)
                    {
                        vo.setRole(apply.getRole());
                    }
                    else if(activity.getCreateUser().getMemberCode().equals(memberCode))
                    {
                        vo.setRole(DKQConstant.ROLES_CREATEER);
                    }
                    else if(activity.getMonitor().getMemberCode().equals(memberCode))
                    {
                        vo.setRole(DKQConstant.ROLES_ADMIN);
                    }
                }
                vos.add(vo);
            }
            resultMap.put("list", vos);
            resultMap.put("page", new DKQPage(data));
            jsonResult.setData(resultMap);
        } catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setMessage(e.getMessage());
            jsonResult.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity(jsonResult,HttpStatus.OK);
    }

    /**
     * 查询指定社团所有的活动
     * @param groupCode
     * @param pageNumber
     * @return
     */
    @RequestMapping(value = "/group/{groupCode}/{pageNumber}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> findByGroup(@PathVariable("groupCode") String groupCode,@PathVariable("pageNumber") int pageNumber)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            Page<Activity>  data = this.activityService.findByGroupCode(groupCode, pageNumber);
            if (data == null || data.getContent() == null || data.getContent().size() ==0)
            {
                String message = "暂无活动数据";
                logger.warn(message);
                jsonResult.setMessage(message);
                jsonResult.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(jsonResult,HttpStatus.OK);
            }
            Map<String,Object> resultMap = new HashMap<String,Object>();

            List<Activity> list = data.getContent();
            List<ActivityVO> vos = new ArrayList<ActivityVO>();
            for(Activity activity:list)
            {
                ActivityRecruit activityRecruit = this.activityRecruitService.findByActivity(activity.getId());
                ActivityVO vo = ActivityVO.buildVO(activity,activityRecruit,ConfigUtil.getClientId());
                vos.add(vo);
            }
            resultMap.put("list", vos);
            resultMap.put("page", new DKQPage(data));
            jsonResult.setData(resultMap);
        } catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setMessage(e.getMessage());
            jsonResult.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity(jsonResult,HttpStatus.OK);
    }

    /**
     * 活动详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/id/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> findOne(@PathVariable("id") Long id)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            Map<String,Object> resultMap = new HashMap<String,Object>();
            Activity activity = activityService.findOne(id);
            if(null == activity)
            {
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage("活动不存在");
                return new ResponseEntity(jsonResult,HttpStatus.OK);
            }

            //查询本次活动的20个报名名单
            List<ActivityApplyVO> vos = new ArrayList<ActivityApplyVO>();
            Page<ActivityApply> applies = this.activityApplyService.queryByActivity(activity.getActivityCode(), DKQConstant.APPLY_STATUS_OK,1);
            if(null != applies && null != applies.getContent() && applies.getContent().size()>0)
            {

                for(ActivityApply activityApply: applies.getContent())
                    vos.add(ActivityApplyVO.buildVO(activityApply));
            }
            ActivityRecruit activityRecruit = this.activityRecruitService.findByActivity(activity.getId());
            ActivityVO activityVO = ActivityVO.buildVO(activity,activityRecruit,ConfigUtil.getClientId());
            //ActivityRecruit activityRecruit = activityRecruitService.findByActivityCode(activity.getActivityCode());
            if(null != activityRecruit)
                activityVO.setIsRecruit(1);

            resultMap.put("activity",activityVO);
            resultMap.put("applys",vos);
            jsonResult.setData(resultMap);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity(jsonResult,HttpStatus.OK);
    }

    /**
     * 活动详情
     * @param activityCode
     * @return
     */
    @RequestMapping(value = "/activityCode/{activityCode}/{memberCode}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> findByActivityCode(@PathVariable("activityCode") String activityCode,@PathVariable("memberCode") String memberCode)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            Activity activity = activityService.findByActivityCode(memberCode,activityCode);
            if(null == activity)
            {
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage("活动不存在");
                return new ResponseEntity(jsonResult,HttpStatus.OK);
            }
            //查询本次活动的20个报名名单
            List<ActivityApplyVO> vos = new ArrayList<ActivityApplyVO>();
            Page<ActivityApply> applies = this.activityApplyService.queryByActivity(activityCode, DKQConstant.APPLY_STATUS_OK,1);
            if(null != applies && null != applies.getContent() && applies.getContent().size()>0)
            {
                for(ActivityApply activityApply: applies.getContent())
                    vos.add(ActivityApplyVO.buildVO(activityApply));
            }
            HashMap<String,Object> resultMap = new HashMap<String, Object>();
            ActivityRecruit activityRecruit = activityRecruitService.findByActivityCode(activityCode);
            ActivityVO activityVO = ActivityVO.buildVO(activity,activityRecruit,ConfigUtil.getClientId());


            //查询当前用户是否报名本次活动
            if(StringUtils.isNotBlank(memberCode) && !"null".equals(memberCode))
            {
                ActivityApply activityApply = activityApplyService.findByVolunteerAndActivityAndStatus(memberCode, activityCode, DKQConstant.APPLY_STATUS_OK);
                if(null == activityApply)
                {
                    activityApply = activityApplyService.findByVolunteerAndActivityAndStatus(memberCode, activityCode, DKQConstant.APPLY_STATUS);
                    if(null == activityApply)
                    {
                        activityVO.setIsApply(DKQConstant.APPLY_UN_APPLY_STATUS);
                        Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
                        activityVO.setIsFinished(volunteer.getIsFinished());
                    }
                    else
                    {
                        activityVO.setIsApply(activityApply.getStatus());
                    }
                }
                else
                {
                   activityVO.setIsApply(activityApply.getStatus());
                }
                //查询用户是否本社团成员
                GroupVolunteer groupVolunteer = groupVolunteerService.findByMemberAndGroup(memberCode, DKQConstant.APPLY_STATUS_ALL, activity.getGroup().getGroupCode());
                if(null != groupVolunteer && (groupVolunteer.getStatus() == DKQConstant.APPLY_STATUS_OK || groupVolunteer.getStatus() == DKQConstant.APPLY_STATUS_FREEZE))
                {
                    activityVO.setIsGroupVolunteer(1);
                }
            }
            else
            {
                activityVO.setIsApply(DKQConstant.APPLY_UN_APPLY_STATUS);
            }

            resultMap.put("activity",activityVO);
            resultMap.put("applys",vos);
            jsonResult.setData(resultMap);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity(jsonResult,HttpStatus.OK);
    }

    /**
     * 活动详情
     * @param activityCode
     * @return
     */
    @RequestMapping(value = "/activityManager/{activityCode}/{memberCode}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> activityManager(@PathVariable("activityCode") String activityCode,@PathVariable("memberCode") String memberCode)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            Activity activity = activityService.activityManager(activityCode);
            if(null == activity)
            {
                jsonResult.setCode(JsonResult.CODE_FAIL);
                jsonResult.setMessage("活动不存在");
                return new ResponseEntity(jsonResult,HttpStatus.OK);
            }
            //查询本次活动的20个报名名单
            List<ActivityApplyVO> vos = new ArrayList<ActivityApplyVO>();
            Page<ActivityApply> applies = this.activityApplyService.queryByActivity(activityCode, DKQConstant.APPLY_STATUS_OK,1);
            if(null != applies && null != applies.getContent() && applies.getContent().size()>0)
            {

                for(ActivityApply activityApply: applies.getContent())
                    vos.add(ActivityApplyVO.buildVO(activityApply));
            }

            ActivityRecruit activityRecruit = activityRecruitService.findByActivityCode(activityCode);
            HashMap<String,Object> resultMap = new HashMap<String, Object>();
            ActivityVO activityVO = ActivityVO.buildVO(activity,activityRecruit,ConfigUtil.getClientId());

            if(null != activityRecruit)
                activityVO.setIsRecruit(1);

            //查询当前用户是否报名本次活动
            if(StringUtils.isNotBlank(memberCode) || !"null".equals(memberCode))
            {
                ActivityApply activityApply = activityApplyService.findByVolunteerAndActivity(memberCode, activityCode);
                if(null == activityApply)
                {
                    activityVO.setIsApply(DKQConstant.APPLY_UN_APPLY_STATUS);
                }
                else
                {

                    if(activityApply.getStatus() != DKQConstant.APPLY_STATUS_EXIT)
                        activityVO.setIsApply(activityApply.getStatus());
                    else
                        activityVO.setIsApply(DKQConstant.APPLY_UN_APPLY_STATUS);
                }
            }
            else
                activityVO.setIsApply(DKQConstant.APPLY_UN_APPLY_STATUS);

            resultMap.put("activity",activityVO);
            resultMap.put("applys",vos);
            jsonResult.setData(resultMap);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
            return new ResponseEntity(jsonResult,HttpStatus.OK);
        }
        return new ResponseEntity(jsonResult,HttpStatus.OK);
    }
    /**
     * 管理员删除指定活动
     * @param param
     * @return
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST,consumes = MediaTypes.JSON,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> delete(@RequestBody String param)
    {
        JsonResult result = new JsonResult();
        try
        {
            //检查非空
            if(StringUtils.isBlank(param))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            //检查当前活动是否发布了招募
            JSONObject jsonObject = JSON.parseObject(param);
            String activityCode = jsonObject.getString("activityCode");
            ActivityRecruit activityRecruit = this.activityRecruitService.findByActivityCode(activityCode);
            if(null != activityRecruit)
            {
                result.setMessage("当前活动有对外招募，请先取消对外招募");
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            this.activityService.delete(param);
            result.setMessage("活动已成功取消");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity<Object>(result, HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }
}
